/***********************************************************************

 Copyright (c) 2009, Luke Malcolm, www.lukemalcolm.com
 Based on ofxFileStream by Todd Vanderlin, www.vanderlin.cc

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

 ***********************************************************************/

#ifndef OFXSMSSQLITESAVETHREAD_H
#define OFXSMSSQLITESAVETHREAD_H

#include "ofMain.h"
#include "ofxThread.h"
#include "ofxSMS.h"
#include "ofxSMSsqliteUtils.h"
#include "ofxSQLiteHeaders.h"
#include <fstream>
#include <iostream>

class ofxSMSsqliteSaveThread : public ofxThread
{
public:

        string      filename;
        ofxSMS *    smsObject;
        //ofxSQLite*  sqlite;

        bool doSave;

		ofxSMSsqliteSaveThread(){

		}

		void start(){
            startThread(true, false);   // blocking, verbose
        }

        void stop(){
            stopThread();
        }

		//--------------------------
		void threadedFunction(){

			while( isThreadRunning() != 0 ){
				if( lock() ){

                    if (doSave) {

                        //write the database to a buffer file, just something happens during the write.
                        string bufferFilename = filename + "_buffer";

                        ofLog(OF_LOG_VERBOSE,"ofxSMSsqlite::save - Saving to buffer: %s\n",bufferFilename.c_str());
                        ofxSQLite * sqliteSave = new ofxSQLite(bufferFilename);

                        processSQLError(sqliteSave->getError(),"ofxSMSsqlite::save - Save DB Error: %s\n");

                        sqliteSave->simpleQuery("DROP TABLE messages");

                        processSQLError(sqliteSave->getError(),"ofxSMSsqlite::save - Drop table Error: %s\n");

                        sqliteSave->simpleQuery(""\
                          "CREATE TABLE IF NOT EXISTS messages (" \
                             " db_id INTEGER PRIMARY KEY AUTOINCREMENT" \
                             " ,uuid TEXT" \
                             " ,message TEXT" \
                             " ,fromN TEXT" \
                             " ,read BOOLEAN" \
                             " ,datetimeBlob BLOB" \
                          ");"
                        );

                        processSQLError(sqliteSave->getError(),"ofxSMSsqlite::save - Create table Error: %s\n");

                        std::vector<ofxSMSMessage>::iterator smsRecord;
                        for(smsRecord = (*smsObject).all.begin(); smsRecord != (*smsObject).all.end(); smsRecord++){

                            sqliteSave->insert("messages")
                            .use("uuid",      smsRecord->id)
                            .use("message", smsRecord->text)
                            .use("fromN",    smsRecord->from)
                            .use("read",    smsRecord->bRead)
                            .use("datetimeBlob",    smsRecord->datetime)
                            .execute();

                        processSQLError(sqliteSave->getError(),"ofxSMSsqlite::save - Insert Record Error: %s\n");

                        }

                        delete sqliteSave;

                        //Now copy the buffer across to the read file place.
                        ofLog(OF_LOG_VERBOSE,"ofxSMSsqlite::save - Copying buffer db file to file: %s\n",filename.c_str());
                        std::ifstream ifs(bufferFilename.c_str(), std::ios::binary);
                        std::ofstream ofs(filename.c_str(), std::ios::binary);

                        ofs << ifs.rdbuf();

                        doSave = false;
                    } //if doSave
                unlock();
				}
			}
		}


};

#endif // OFXSMSSQLITESAVETHREAD_H
